package com.liao.furns.web; /**
 * @author lzp
 * @version 1.0
 * lzpnb!
 */

import com.liao.furns.pojo.Furn;
import com.liao.furns.pojo.Member;
import com.liao.furns.pojo.Page;
import com.liao.furns.service.FurnService;
import com.liao.furns.service.impl.FurnServiceImpl;
import com.liao.furns.utils.DataUtils;
import com.liao.furns.utils.WebUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

public class FurnServlet extends BasicServlet {
    private FurnService furnService = new FurnServiceImpl();

    public void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        Page<Furn> page = furnService.page(pageNo,pageSize);
        System.out.println(page);
        request.setAttribute("page",page);
        request.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(request,response);
    }

    public void updateFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        int i = DataUtils.parseInt(id, 0);
        Furn furn = furnService.queryFurnById(i);

        if(ServletFileUpload.isMultipartContent(request)){
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            servletFileUpload.setHeaderEncoding("utf-8");
            try {
                List<FileItem> list = servletFileUpload.parseRequest(request);
//                System.out.println("list = " + list);
                for (FileItem fileItem : list) {
//                    System.out.println(fileItem);
                    if(fileItem.isFormField()){
                        if("name".equals(fileItem.getFieldName())){
                            furn.setName(fileItem.getString("utf-8"));
                        }else if ("maker".equals(fileItem.getFieldName())){
                            furn.setMaker(fileItem.getString("utf-8"));
                        }else if ("price".equals(fileItem.getFieldName())){
                            furn.setPrice(new BigDecimal(fileItem.getString("utf-8")));
                        }else if ("stock".equals(fileItem.getFieldName())){
                            furn.setStock(new Integer(fileItem.getString("utf-8")));
                        } else if ("sales".equals(fileItem.getFieldName())){
                            furn.setStock(new Integer(fileItem.getString("utf-8")));
                        }
                    }else {
                        String name2 = fileItem.getName();
                        if(!"".equals(name2)) {
                            System.out.println("上传的文件名=" + name2);
                            String filepath = "/" + WebUtils.FURN_IMG_PATH;
                            String filerealpath = request.getServletContext().getRealPath(filepath);
                            File file = new File(filerealpath);
                            if (!file.exists()) {
                                file.mkdirs();
                            }
                            name2 = UUID.randomUUID().toString() + "_" + System.currentTimeMillis() + "_" + name2;
                            String filefullpath = file + "/" + name2;
                            fileItem.write(new File(filefullpath));
                            fileItem.getOutputStream().close();
                            furn.setimgPath(WebUtils.FURN_IMG_PATH + "/" + name2);
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else {
            System.out.println("不是文件表单");
        }
            furnService.updateFurn(furn);
            System.out.println("修改成功");
            request.getRequestDispatcher("/views/manage/update_ok.jsp").forward(request,response);
    }

//    public void updateFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        Furn furn = DataUtils.copyParamToBean(request.getParameterMap(),new Furn());
////        System.out.println("chuanjianchenggong");
////        System.out.println(furn);
//        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
//        if(furnService.updateFurn(furn) == 1 ){
//            System.out.println("修改成功");
//            response.sendRedirect(request.getContextPath() + "/manage/FurnServlet?action=page&pageNo=" + pageNo);
//        }else {
//            request.getRequestDispatcher("/views/manage/furn_update.jsp").forward(request,response);
//        }
//    }

    public void showFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        int i = DataUtils.parseInt(id, 0);
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
        request.setAttribute("pageNo",pageNo);
        Furn furn = furnService.queryFurnById(i);
        request.setAttribute("furn",furn);
        request.getRequestDispatcher("/views/manage/furn_update.jsp").forward(request,response);
    }

    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Furn> furns = furnService.queryFurns();
            request.setAttribute("furns",furns);
            request.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(request,response);
    }

    public void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = DataUtils.parseInt(request.getParameter("id"),0);
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
        furnService.deleteFurnByid(id);
        response.sendRedirect(request.getContextPath() + "/manage/FurnServlet?action=page&pageNo=" + pageNo);
    }


    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String  name = request.getParameter("name");
//        String  maker = request.getParameter("maker");
//        String  price = request.getParameter("price");
//        String  sales =request.getParameter("sales");
//        String  stock = request.getParameter("stock");
//        int sale = 0;
//        int stocks = 0;
//        BigDecimal prices = null;
//        try {
//            prices = new BigDecimal(sales);
//            sale = Integer.parseInt(sales);
//            stocks = Integer.parseInt(stock);
//        }catch (NumberFormatException e){
//            request.setAttribute("errormsg","添加的数据格式不对！");
//            request.getRequestDispatcher("/views/manage/furn_add.jsp").forward(request,response);
//            return;
//        }
//        String  imgPath = "assets/images/product-image/default.jpg";
//        Furn furn = new Furn(null, name, maker, prices, sale, stocks, imgPath);
        Furn furn = DataUtils.copyParamToBean(request.getParameterMap(),new Furn());
        int pageNo = DataUtils.parseInt(request.getParameter("pageNo"), 1);
        if(furnService.add(furn)){
            System.out.println("添加成功");
//            request.getRequestDispatcher("/manage/FurnServlet?action=list").forward(request,response);
            response.sendRedirect(request.getContextPath() + "/manage/FurnServlet?action=page&pageNo=" + pageNo);
        }else {
            request.getRequestDispatcher("/views/manage/furn_add.jsp").forward(request,response);
        }
    }
}
